package com.atguigu.listen;


import com.atguigu.config.MqConst;
import com.atguigu.respority.ScheduleRepository;
import com.atguigu.service.RabbitService;
import com.atguigu.service.ScheduleService;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;

/**
 *   监听 订单服务
 */
public class HospitalReceiver {
    @Autowired
    private ScheduleService   scheduleService;
    @Autowired
    private RabbitService  rabbitService;
    @Autowired
    private ScheduleRepository scheduleRepository;
    //监听指定队列  监听订单服务
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_ORDER,durable = "true"), //监听的订单服务
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER)//监听第一个队列使用的交换机
            ,key = {MqConst.ROUTING_ORDER})) //交换机所绑定的队列
    //发送消息
    public void  receiver(OrderMqVo orderMqVo, Message message, Channel channel) {
        //创建订单
        if(null != orderMqVo.getAvailableNumber()) {
            Schedule schedule = scheduleService.getById(orderMqVo.getScheduleId());
            schedule.setReservedNumber(orderMqVo.getReservedNumber());
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
            scheduleService.update(schedule);
        } else {
            //取消订单
            Schedule schedule = scheduleService.getById(orderMqVo.getScheduleId());
            int availableNumber = schedule.getAvailableNumber().intValue() + 1;//剩余预约数+1
            schedule.setAvailableNumber(availableNumber);
            scheduleService.update(schedule);
        }
        //发送消息
        MsmVo msmVo = orderMqVo.getMsmVo();
        if(msmVo!=null){
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM,MqConst.ROUTING_MSM_ITEM,msmVo);
        }

    }

}
